package upload

import (
	"crypto/md5"
	"encoding/hex"
	"net/http"
	"strings"

	"gitee.com/zoneaurora/shop/internal/common"
	"github.com/gin-gonic/gin"
)

func Upload(c *gin.Context) {
	// 获取请求中的文件
	file, err := c.FormFile("file")
	if err != nil {
		common.JSON(c, http.StatusBadRequest, "上传失败", nil)
		return
	}

	// 处理文件名
	fileStrings := strings.Split(file.Filename, ".")
	md5 := GenMD5(fileStrings[0])

	// 保存文件
	dst := "./uploads/" + md5[:16] + "." + fileStrings[1]
	err = c.SaveUploadedFile(file, dst)
	if err != nil {
		common.JSON(c, http.StatusInternalServerError, "上传失败", nil)
		return
	}
	common.JSON(c, http.StatusOK, "上传成功", gin.H{
    "path": dst[1:],
  })
}

func GenMD5(str string) string {
	data := []byte(str)
	m := md5.New()
	m.Write(data)
	return hex.EncodeToString(m.Sum(nil))
}
